<script setup lang="ts">
import type { Component } from 'vue';
import { useAttrs } from 'vue';
import { useDebounceFn } from '@vueuse/core';

interface Slots {
  default(): Component;
  footer?(): Component;
}

interface Props {
  loading?: boolean;
  submitBtnText?: string;
  showSubmitBtn?: boolean;
  showCancelBtn?: boolean;
}

interface Emits {
  (e: 'handleCancel'): void;
  (e: 'handleSubmit'): void;
}

defineOptions({ name: 'CustomModal' });

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  submitBtnText: '确 定',
  showSubmitBtn: true,
  showCancelBtn: true
});

const emit = defineEmits<Emits>();

const slots = defineSlots<Slots>();

const visible = defineModel<boolean>('visible', { required: true });

const attrs = useAttrs();

function handleCancel() {
  visible.value = false;
  emit('handleCancel');
}

const handleSubmit = useDebounceFn(
  () => {
    emit('handleSubmit');
  },
  250,
  { maxWait: 1000 }
);
</script>

<template>
  <NModal
    v-model:show="visible"
    :closable="false"
    close-on-esc
    :mask-closable="false"
    preset="card"
    auto-focus
    v-bind="attrs"
    class="n-model-custom"
  >
    <slot name="default"></slot>
    <template #footer>
      <slot v-if="slots.footer"></slot>
      <template v-else>
        <NSpace justify="center" :size="12">
          <NButton v-if="props.showCancelBtn" @click="handleCancel">取 消</NButton>
          <NButton v-if="props.showSubmitBtn" type="primary" :loading="props.loading" @click="handleSubmit">
            {{ props.submitBtnText }}
          </NButton>
        </NSpace>
      </template>
    </template>
  </NModal>
</template>

<style lang="scss">
.n-model-custom {
  .n-card-header {
    font-size: 14px;
    padding: 0 20px;
    line-height: 40px;
    background-color: rgb(var(--primary-color));
    .n-card-header__main {
      color: #ffffff;
    }
  }
  .n-card__content {
    padding: 16px 20px;
  }
  .n-card__footer {
    // padding-bottom: 12px;

    .n-button {
      min-width: 100px;
      height: 30px;
    }
  }
}
</style>
